<?php
class Code{
	private $width;
	private $height;
	private $code;
	//字符个数
	private $num;
	private $im;
	private $codeSize;

	public function __construct($num=4,$width=100,$height=30,$codeSize=18)
	{
		$this->num=$num;
		$this->width=$width;
		$this->height=$height;
		$this->codeSize=$codeSize;
	}
	public function show()
	{
		$this->create_img();
		$this->set_code();
		$this->write_code();
		$this->create_line();
		header('Content-type:image/png');
		imagepng ($this->im);
		imagedestroy ($im);
	}
	public function set_code()
	{
		$str='qwertyuiopasdfghjkl123456789adfghj';
		$code='';
		// $strlen=strlen($str);
		for ($i=0; $i < $this->num; $i++) { 
			$code.=$str[mt_rand(0,strlen($str)-1)];
		}
		$this->code=strtoupper($code);
		$_SESSION['code']=$this->code;
	}

	//创建画布
	public function create_img()
	{
		if (extension_loaded('GD')) {
			//创建画布
			$im=imagecreatetruecolor($this->width, $this->height);
			//设置颜色，白色
			$white=imagecolorallocate($im, 255, 255, 255);
			//填充颜色 不填充时默认为黑色
			imagefill($im, 0, 0, $white);
			$color = imagecolorallocate($im, 188, 188, 188);
			imagerectangle($im, 0, 0, $this->width-1, $this->height-1, $color);
			$this->im=$im;

		}else{
			echo "没检测到GD库";
		};
	}
	//写入字符
	public function write_code()
	{
		$fontfile=CWF_PATH.'Data/font/font.TTF';
		$w=$this->width/$this->num;
		for ($i=0; $i < $this->num; $i++) { 
			$color=imagecolorallocate($this->im, mt_rand(0,150), mt_rand(0,150), mt_rand(0,150));
		$x=$i*$w+5;
		imagettftext($this->im, $this->codeSize, mt_rand(-2,20), $x, $this->height*0.8, $color, $fontfile, $this->code[$i]);

		}
	}

	//设置干扰
	public function create_line()
	{
		
		for ($i=0; $i < $this->num; $i++) { 
			$color=imagecolorallocate($this->im, mt_rand(0,200), mt_rand(0,200), mt_rand(0,200));
			imageLine($this->im,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
		}

		for($v=0;$v<100;$v++){
			imagesetpixel($this->im, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
		}

	}

}